<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/3/19
 * Time: 17:40
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\common\lib\map;


use app\common\lib\Show;
use app\common\lib\Status;
use think\Exception;

class Tencent extends Base
{
    protected string $keywords_url = "https://apis.map.qq.com/ws/place/v1/suggestion";

    /**
     * 关键词提示
     * @param string $keyword 搜索关键词
     * @param string $region 城市
     * @param string $key 密钥
     * @param int $page_index 分页
     * @param int $page_size 每页显示数
     * @param int $region_fix 0[默认]当前城市无结果时，自动扩大范围到全国匹配  1：固定在当前城市
     * @return array
     * @throws Exception
     */
    public function suggestion(string $keyword = "", string $region = "", string $key = "", int $page_index = 1, int $page_size = 20, int $region_fix = 1): array
    {
        if (empty($keyword)) {
            throw new Exception("请输入搜索词");
        }
        $data = [
            "keyword" => $keyword,
            "region" => $region,
            "page_index" => $page_index,
            "page_size" => $page_size,
            "region_fix" => $region_fix,
            "key" => $key
        ];
        try {
            $result = $this->__get_url($this->keywords_url . "?" . http_build_query($data));
        } catch (\Exception $exception) {
            throw new Exception($exception->getMessage());
        }
        $res = json_decode($result, true);

        if ($res['status'] == 0) {
            if (strstr($res['message'], "ok")) {
                //返回的格式应该是  name value lat lng
                $lists = [];
                foreach ($res['data'] as $value){
                    $lists[] = [
                        "name"=>$value['title'],
                        "value"=>$value['location']['lat']."~".$value['location']['lng'],
                        "lat"=>$value['location']['lat'],
                        "lng"=>$value['location']['lng']
                    ];
                }
                return Show::json_show(Status::status_normal, "ok", $lists, 0, true);
            } else {
                return Show::json_show(Status::status_error, $res['message'], [], 0, true);
            }
        } else {
            return Show::json_show(Status::status_error, $res['message'], [], 0, true);
        }
    }
}